package com.zyh.answer.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyh.answer.domain.AnalyzeDataObj;
import com.zyh.answer.domain.SymptomCluster;
import com.zyh.answer.domain.SymptomClusterDTO;
import com.zyh.answer.domain.UserAnswer;
import com.zyh.answer.mapper.UserAnswerMapper;
import com.zyh.answer.service.UserAnswerService;
import com.zyh.common.core.domain.AjaxResult;
import com.zyh.common.utils.SecurityUtils;
import com.zyh.exam.domain.ExamPaper;
import com.zyh.exam.service.IExamPaperService;
import com.zyh.question.domain.ExamQuestion;
import com.zyh.question.service.IExamQuestionService;
import com.zyh.record.domain.ExamRecord;
import com.zyh.record.service.ExamRecordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 针对表【t_user_answer】的数据库操作Service实现
 *
 * @author ZYH
 * @description
 * @createDate 2025-03-02 20:29:11
 */
@Service
public class UserAnswerServiceImpl extends ServiceImpl<UserAnswerMapper, UserAnswer>
        implements UserAnswerService {
    public static final Logger logger = LoggerFactory.getLogger(UserAnswerServiceImpl.class);

    @Autowired
    private ExamRecordService examRecordService;

    @Autowired
    private IExamQuestionService examQuestionService;

    @Autowired
    private IExamPaperService examPaperService;
    @Autowired
    private UserAnswerMapper userAnswerMapper;

    @Override
    public AnalyzeDataObj getScore(Long paperId, String delFlag, Long recordId) {
        logger.info("入参paperId-->{},delFlag-->{},recordId-->{}", paperId, delFlag, recordId);
        LambdaQueryWrapper<ExamRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ExamRecord::getUserId, SecurityUtils.getUserId())
                .eq(ExamRecord::getPaperId, paperId)
                .eq(ExamRecord::getStatus, "1")
                .eq(ExamRecord::getDelFlag, delFlag);

        if (recordId != null) {
            wrapper.eq(ExamRecord::getId, recordId);
        }
        // 判断record表中的status是否为1
        ExamRecord examRecord = examRecordService.getOne(wrapper);
        if (Objects.isNull(examRecord)) {
            return null;
        }
        // 根据userAnswerList 查询出各个因子的总分
        List<UserAnswer> userAnswerList = this.list(new LambdaQueryWrapper<UserAnswer>()
                .eq(UserAnswer::getUserId, SecurityUtils.getUserId())
                .eq(UserAnswer::getPaperId, paperId)
                .eq(UserAnswer::getRecordId, examRecord.getId()));
        List<SymptomClusterDTO> symptomClusterDTOList = new ArrayList<>();

        if (Objects.nonNull(userAnswerList) && !userAnswerList.isEmpty()) {
            // 获取题目映射关系
            Set<Long> questionIds = userAnswerList.stream()
                    .map(UserAnswer::getQuestionId)
                    .collect(Collectors.toSet());
            Map<Long, ExamQuestion> questionMap = examQuestionService.listByIds(questionIds)
                    .stream()
                    .collect(Collectors.toMap(ExamQuestion::getId, Function.identity()));

            // 分组求和
            Map<SymptomCluster, Integer> clusterScores = userAnswerList.stream()
                    // 过滤掉没有度量因子映射关系的题目
                    .filter(answer -> {
                        ExamQuestion question = questionMap.get(answer.getQuestionId());
                        return question != null && question.getSymptomCluster() != null;
                    })
                    .collect(Collectors.groupingBy(
                            answer -> SymptomCluster.fromCode(questionMap.get(answer.getQuestionId()).getSymptomCluster()),
                            Collectors.summingInt(UserAnswer::getScore)
                    ));

            // 初始化所有因子类型（确保即使得分为0也返回）
            symptomClusterDTOList = Arrays.stream(SymptomCluster.values())
                    .map(cluster -> {
                        SymptomClusterDTO dto = new SymptomClusterDTO();
                        dto.setName(cluster.getName());
                        dto.setScore(clusterScores.getOrDefault(cluster, 0)); // 获取累计得分
                        dto.setDesc(cluster.getDesc());
                        return dto;
                    })
                    .collect(Collectors.toList());
        }

        // 查询测评卷标题
        ExamPaper examPaper = examPaperService.getById(paperId);
        if (examPaper == null) {
            return null;
        }

        return getAnalyzeDataObj(examRecord, examPaper, symptomClusterDTOList);
    }

    @Override
    public AjaxResult resumeAssessment(Long paperId) {
        // 根据userId,paperId,status查询出record对象
        ExamRecord examRecord = examRecordService.getOne(
                new LambdaQueryWrapper<ExamRecord>()
                        .eq(ExamRecord::getUserId, SecurityUtils.getUserId())
                        .eq(ExamRecord::getPaperId, paperId)
                        .in(ExamRecord::getStatus, "0", "2")
                        .eq(ExamRecord::getDelFlag, "0"));
        List<UserAnswer> userAnswerList = null;
        List<Object> answerList = null;
        if ((Objects.nonNull(examRecord))) {
            userAnswerList = userAnswerMapper.selectList(
                    new LambdaQueryWrapper<UserAnswer>()
                            .eq(UserAnswer::getUserId, SecurityUtils.getUserId())
                            .eq(UserAnswer::getPaperId, paperId)
                            .eq(UserAnswer::getRecordId, examRecord.getId())
                            .eq(UserAnswer::getDelFlag, "0"));
        }
        if (Objects.nonNull(userAnswerList)) {
            answerList = userAnswerList.stream()
                    .map(UserAnswer::getAnswer).collect(Collectors.toList());
        }
        HashMap<String, Object> map = new HashMap();
        map.put("answerList", answerList);
        map.put("examRecord", examRecord);  // 将时间返回
        return AjaxResult.success(map);
    }

    // 封装返回数据
    private static AnalyzeDataObj getAnalyzeDataObj(ExamRecord examRecord, ExamPaper examPaper, List<SymptomClusterDTO> symptomClusterDTOList) {
        Long totalTime = examRecord.getTotalTime();
        AnalyzeDataObj analyzeDataObj = new AnalyzeDataObj();
        analyzeDataObj.setRecordId(examRecord.getId());
        analyzeDataObj.setPaperTitle(examPaper.getTitle());
        analyzeDataObj.setSubmitTime(examRecord.getSubmitTime());
        analyzeDataObj.setTotalTime(totalTime);
        analyzeDataObj.setStatus(examRecord.getStatus());
        analyzeDataObj.setTotalScore(examRecord.getTotalScore());
        analyzeDataObj.setSymptomClusterDTOList(symptomClusterDTOList);
        return analyzeDataObj;
    }
}




